import * as echarts from "echarts";
import lessModule from "./index.module.less"
import { useEffect, useState } from "react"
import { $echartsData, $eventBus } from "../../../../common/utils";
import { modeType } from "../../../../common/interface";
// 主页-单条折线图表组件
interface homePageChartLineComponentComponentInterface {
    id: string
    name: string
    mode?: modeType
    color: string
    isWarningLine: boolean
    sourceData: object
    zoomList?: Array<number>
    change_zoomList?: Function
}
const HomePage_ChartLineComponent: React.FC<homePageChartLineComponentComponentInterface> = (props) => {
    let [echartsLine, setEchartsLine] = useState<echarts.ECharts>()

    const init_echarts = () => {
        echartsLine = echarts.init(document.getElementById(props.id) as HTMLElement)
        setEchartsLine(echartsLine)
        window.addEventListener("resize", () => {
            echartsLine?.resize();
        })
        echartsLine?.on("dataZoom", (data) => {
            const tempData = data?.["batch"] ? data["batch"][0] : data

            props?.change_zoomList?.([tempData["start"], tempData["end"]])
        })
        draw_echarts()
    }

    const draw_echarts = () => {
        const echartsOption = {
            tooltip: {
                trigger: "axis",
                backgroundColor: "#FFFFFF",
                textStyle: {
                    fontSize: 12,
                    fontWeight: 400,
                },
                axisPointer: {
                    lineStyle: {
                        type: "solid",
                        color: "rgba(64, 93, 249, 0.5)",
                    }
                },
                formatter(list: Array<Object>) {
                    emit_cursorValue(typeof (list[0]["value"]) === "number" ? list[0]["value"].toFixed(2) : "-")
                    return `<div class="homePage-chartTooltip">
                        <div class="homePage-chartTooltip__title">${list[0]['axisValue']}</div>
                        <div class="homePage-chartTooltip__row">
                            <div class="chartTooltip-row__legend" style="background-color:${$echartsData["chartLineColorList"][0]}"></div>
                            <span>${list[0]["seriesName"]}</span>
                            <span style="color:${$echartsData["chartLineColorList"][0]}">${typeof (list[0]["value"]) === "number" ? list[0]["value"].toFixed(2) : "-"}</span>
                        </div>
                    </div>`;
                },
            },
            
            legend: {
                show: props.name !== "zoomAxis",
                left: "left",
                icon: "rect",
                padding: [0, 40],
                itemWidth: 10,
                itemHeight: 2,
                textStyle: {
                    color: "rgba(0, 0, 0, 0.85)"
                }
            },
            grid: {
                top: props.name === "zoomAxis" ? $echartsData["zoomAxisHeight"] : 70,
                left: 54,
                bottom: 45,
                right: 90,
            },
            xAxis: {
                type: "category",
                data: props.sourceData["time"],
                boundaryGap: false,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(65, 97, 128, 0.45)",
                    },
                },
                axisTick: {
                    show: true,
                    lineStyle: {
                        color: "rgba(65, 97, 128, 0.35)",
                    },
                },

                axisLabel: {
                    align: "center",
                    color: "rgba(0, 0, 0, 0.65)",
                    margin: 20,
                    fontSize: 10,
                    showMinLabel: true,
                    showMaxLabel: true,
                    formatter: (() => {
                        return (item: Object, idx: number) => {
                            const isStart = !idx
                            const isLast = idx === props.sourceData["time"]?.length - 1;
                            const label = isStart ? `{start|${item}}` : isLast ? `{last|${item}}` : item;
                            return label;
                        };
                    })(),
                    interval: props.sourceData["time"]?.length / 4,
                    rich: {
                        start: {
                            width: 0,
                            fontSize: 10,
                            align: "left",
                        },
                        last: {
                            width: 0,
                            fontSize: 10,
                            align: "right",
                        },
                    },
                },
            },
            yAxis: {
                type: "value",
                axisLabel: {
                    fontSize: 12,
                    fontWeight: 400,
                    color: "rgba(0, 0, 0, 0.65)",
                },
                splitLine: {
                    lineStyle: {
                        color: "rgba(65, 97, 128, 0.1519)",
                    },
                },
            },
            dataZoom: [
                {
                    type: props.name === "zoomAxis" ? 'slider' : "inside",
                    disabled: !props.zoomList,
                    ...$echartsData["zoomAxisConfigureData"]
                }
            ],
            series: [
                {
                    name: props.name,
                    data: props.name === "zoomAxis" ? [] : props.sourceData["data"],
                    type: "line",
                    color: props.color,
                    symbol: "none",
                    // smooth: true,
                    animation: false,
                    markLine: props.isWarningLine ? {
                        silent: true,
                        symbol: "none",
                        data: [
                            {
                                yAxis: 30,
                                lineStyle: {
                                    color: $echartsData["charWarningLineColorList"][0]
                                },
                                label: {
                                    color: $echartsData["charWarningLineColorList"][0],
                                    formatter: `一级预警(${30})`
                                }
                            },
                            {
                                yAxis: 20,
                                lineStyle: {
                                    color: $echartsData["charWarningLineColorList"][1]
                                },
                                label: {
                                    color: $echartsData["charWarningLineColorList"][1],
                                    formatter: `二级预警(${20})`
                                }
                            },
                        ],
                        lineStyle: {
                            type: 'solid',
                            width: 1
                        },
                    } : {},
                },

            ],
        }

        echartsLine?.setOption(echartsOption);
    }
  
    const emit_cursorValue = (value: string) => {
        props.id.includes("chartListItem") && setTimeout(() => {
            $eventBus.emit("cursorValue", { source: "HomePage_ChartLineComponent", explain: "图表游标值已发送！", data: { idx: parseInt(props.id.split("chartListItem")[1]), value } })
        });
    }
    const mouseOut_chart = () => {
        emit_cursorValue("-")
    }

    useEffect(() => {
        init_echarts()
        return () => {
            echartsLine?.dispose()
        }
    }, [props.id, props.isWarningLine, props.sourceData])

    useEffect(() => {
        echartsLine?.setOption({
            dataZoom: [{
                start: props?.zoomList?.[0],
                end: props?.zoomList?.[1]
            }]
        })
    }, [props.zoomList])


    return (
        <div id={props.id} className={lessModule["homePageChartLineComponent"]} onMouseOut={mouseOut_chart}></div>
    )
}



export default HomePage_ChartLineComponent